<?php
declare (strict_types=1);

namespace app\api\controller\v1;

use app\api\validate\TopicValidate;
use app\common\model\Degree;
use app\common\model\Major;
use app\common\model\Paper;
use app\common\model\Subject;
use app\common\model\Types;
use app\common\model\Topic as TopicModel;
use think\exception\ValidateException;

class Topic extends BaseController
{
    /**
     * 获取随机组卷信息
     *
     * @return \think\Response
     */
    public function topic()
    {
        //  获取页数
        $page = input('page/d', 1);
        //  获取每页条数
        $num = input('num/d', 2);
        //  历史组卷信息
        $papers = Paper::where(['status' => 1, 'student_id' => 1])
            ->field('id,title,create_at')
            ->page($page, $num)
            ->order('create_at desc')  //  根据创建时间倒序，将新生成组卷显示在最上面
            ->select();
        //  总条数
        $rows = Paper::where(['status' => 1, 'student_id' => 1])->field('id,title,create_at')->count();
        //  最大页数
        $maxPage = ceil($rows / $num);
        //  科目
        $majors = Major::where(['status' => 1])->field('id,name')->select();
        //  试卷类型
        $types = Types::where(['status' => 1])->field('id,name')->select();
        //  难易程度
        $degrees = Degree::where(['status' => 1])->field('id,title')->select();
        //  请求成功返回信息
        $data = ['papers' => $papers, 'rows' => $rows, 'num' => $num, 'maxPage' => $maxPage, 'page' => $page, 'majors' => $majors, 'types' => $types, 'degrees' => $degrees];
        return sucessMsg(200, '获取成功！', $data);
    }

    /*
     * 生成随机组卷
     *
     */
    public function create()
    {
        $paperModel = new Paper();
        $data = input('post.');
        try {
            validate(TopicValidate::class)->scene('create')->check($data);
            $paper['student_id'] = $this->user_id;  //  获取当前登录学生id
            $paper['type'] = 3;  //  随机组卷（type=3）
            $paper['title'] = $data['title'];  //  试卷名称
            //  生成试卷
            $p_res = $paperModel->save($paper);
            if (!$p_res)
                return errMsg(400, '服务器错误,请稍后再试...');
            //  生成试卷成功后获取试卷id
            $paper_id = $paperModel->id;
            //  根据学生所选难易程度随机组题
            if ($data['degree_id'] == 1) {
                //  简单
                //  选择题:10,填空题:10,判断题:5,问答题:3
                $xuanze_num = 10;
                $tainkong_num = 10;
                $panduan_num = 5;
                $wenda_num = 3;
            } elseif ($data['degree_id'] == 2) {
                //  中等
                //  选择题:10,填空题:10,判断题:7,问答题:3
                $xuanze_num = 10;
                $tainkong_num = 10;
                $panduan_num = 7;
                $wenda_num = 3;
            } elseif ($data['degree_id'] == 3) {
                //  困难
                //  选择题:15,填空题:15,判断题:10,问答题:5
                $xuanze_num = 15;
                $tainkong_num = 15;
                $panduan_num = 10;
                $wenda_num = 5;
            }
            //  随机抽题放入topic表中
            $xuanze = $panduan = $tiankong = $wenda = [];
            foreach ($data['type_id'] as $v) {
                //1=选择,2=判断,3=填空,4=问答
                $where = ['status' => 1, 'types_id' => $v, 'degree_id' => $data['degree_id'], 'major_id' => $data['major_id']];
                $count = Subject::where($where)->count();
                $rand = mt_rand(1, $count);
                $limit = $rand . ',' . $count;
                $list = Subject::where($where)->select()->toArray();
                shuffle($list);
                if ($v == 1) {
                    $xuanze = array_slice($list, 0, $xuanze_num);
                }
                if ($v == 2) {
                    $panduan = array_slice($list, 0, $panduan_num);
                }
                if ($v == 3) {
                    $tiankong = array_slice($list, 0, $tainkong_num);
                }
                if ($v == 4) {
                    $wenda = array_slice($list, 0, $wenda_num);
                }
            }
            //  获取随机题目id
            $topic = implode(',', array_column(array_merge_recursive($xuanze, $panduan, $tiankong, $wenda), 'id'));
            //  将数据存入试卷题目表（topic）
            $t_res = TopicModel::create(['paper_id' => $paper_id, 'subject_id' => $topic]);
            if (!$t_res)
                return errMsg(400, '组卷失败，请稍后再试！');
            //  组卷成功返回信息
            return sucessMsg(200, '组卷成功！');
            //  前端根据状态码刷新，重新请求index，新生成组卷展示在左侧
        } catch (ValidateException $e) {
            return errMsg(400, $e->getError());
        }
    }
}

